package com.sky.zzh.today;

import java.io.File;
import java.io.FileOutputStream;
import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import cn.sharesdk.onekeyshare.OneKeyShareCallback;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.zzh.BaseFragment;
import com.sky.zzh.R;
import com.sky.zzh.adapter.TimeAdapter;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;

/**
 * 离床 和 体动
 * 
 * @author skypan
 * 
 */
public class LeaveBedFragment extends BaseFragment implements ITaskListener {
	public static final int TYPEGETUP = 1;
	public static final int TYPETURNUP = 2;

	private TextView mLabel, mTvHours, mTvTimes,mTvMins;
	private ImageView mIvTubiao;
	private ListView mLvRecord;
	private int type = 1;
	private SHGet getUpTask;
	private String fromDate = "20150926", endDate = "20150927";
	private TextView mTvTitle;
	private Button mBtnBack, mBtnShare;

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		mLabel = (TextView) view.findViewById(R.id.label_text);
		mTvHours = (TextView) view.findViewById(R.id.tv_hours);
		mTvTimes = (TextView) view.findViewById(R.id.tv_times);
		mIvTubiao = (ImageView) view.findViewById(R.id.iv_tubiao);
		mLvRecord = (ListView) view.findViewById(R.id.lv_record);
		mTvTitle = (TextView) view.findViewById(R.id.tv_title);
		mBtnBack = (Button) view.findViewById(R.id.btn_back);
		mBtnShare = (Button) view.findViewById(R.id.btn_right);
		mTvMins = (TextView) view.findViewById(R.id.tv_mins);
		type = getActivity().getIntent().getIntExtra("TYPE", 1);
		mBtnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				getActivity().finish();
			}
		});

		mBtnShare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				GetandSaveCurrentImage();
				showShare(false, null, false);
			}
		});

		if (type == TYPEGETUP) {
			mTvTitle.setText("离床");
			mLabel.setText("您昨晚离床");
			mIvTubiao.setBackgroundResource(R.drawable.ic_getup);
		} else if (type == TYPETURNUP) {
			mTvTitle.setText("体动");
			mLabel.setText("您昨晚体动");
			mIvTubiao.setBackgroundResource(R.drawable.ic_body_movement);
		}

		fromDate = getActivity().getIntent().getStringExtra("fromDate");
		endDate = getActivity().getIntent().getStringExtra("endDate");

		int times = getActivity().getIntent().getIntExtra("times", 0);
		mTvTimes.setText(times + "");
		if (CommonUtil.isEmpty(getActivity().getIntent().getStringExtra("sleep"))) {
			mTvHours.setText("0");
			mTvMins.setText("0");
		} else {
//			mTvHours.setText(getActivity().getIntent().getStringExtra("sleep"));
			
			String ave = getActivity().getIntent().getStringExtra("sleep");
			if (!"".equals(ave)) {

				String[] split = ave.split("\\.");
				int hour = Integer.valueOf(split[0]);
				int minute = 0;
				if (split.length > 1) {
					minute = Integer.valueOf(split[1]);
				}
				mTvHours.setText(hour + "");
				mTvMins.setText(minute * 60 / 100 + "");
			} else {
				mTvHours.setText(0 + "");
				mTvMins.setText(0 + "");
			}
		}
		if (times != 0) {
			requestData();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_leave_bed, container, false);
		return view;
	}

	private void requestData() {
		getUpTask = new SHGet();
		getUpTask.setListener(this);
		StringBuffer sb = new StringBuffer();
		sb.append(ConfigDefinition.URL);
		sb.append("app/SensorDataHistory?UUID=");
		sb.append(UserInfoManager.getInstance().getUUID());
		// sb.append("MT003");
		sb.append("&");
		if (type == TYPEGETUP) {
			sb.append("DataProperty=2&FromDate=");
		} else {
			sb.append("DataProperty=1&FromDate=");
		}
		sb.append(fromDate);
		sb.append("&");
		sb.append("EndDate=");
		sb.append(endDate);
		sb.append("&FromTime=18:00&EndTime=18:00");
		getUpTask.setUrl(sb.toString());
		getUpTask.start();
	}

	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject(task.getResult().toString());
		System.out.println("json:" + json);
		if (task == getUpTask) {
			if ("200".equals(json.optString("ReturnCode"))) {
				// PropertyCode 1:体动 2:离床
				JSONArray jsonArray = json.optJSONArray("SensorData");
				JSONArray tempArray = null;
				for (int i = 0; i < jsonArray.length(); i++) {
					if (type == TYPEGETUP) {// 离床
						if ("2".equals(jsonArray.optJSONObject(i).optString("PropertyCode"))) {
							tempArray = jsonArray.optJSONObject(i).optJSONArray("Data");
							break;
						}
					} else {// 体动
						if ("1".equals(jsonArray.optJSONObject(i).optString("PropertyCode"))) {
							tempArray = jsonArray.optJSONObject(i).optJSONArray("Data");
							break;
						}
					}
				}

				JSONArray newArray = new JSONArray();

				for (int i = 0; i < tempArray.length(); i++) {
					if ("1".equals(tempArray.optJSONObject(i).optString("Value"))) {
						newArray.put(tempArray.optJSONObject(i));
					}
				}

				TimeAdapter adapter = new TimeAdapter(getActivity(), newArray);
				mLvRecord.setAdapter(adapter);

			}
		}
	}

	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub

	}

	private String getSDCardPath() {
		File sdcardDir = null;
		boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
		if (sdcardExist) {
			sdcardDir = Environment.getExternalStorageDirectory();
		}
		return sdcardDir.toString();
	}

	private void showShare(boolean silent, String platform, boolean captureView) {
		final OnekeyShare oks = new OnekeyShare();

		// oks.setAddress("12345678901");
		oks.setTitle("智照护");
		// oks.setTitleUrl("http://mob.com");
		oks.setText("");
		oks.setImagePath(getSDCardPath() + "/zzh/ScreenImages" + "/Screen_share.png");
		// oks.setImagePath(CustomShareFieldsPage.getString("imagePath",
		// MainActivity.TEST_IMAGE));
		// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");
		// oks.setImageArray(new String[]{MainActivity.TEST_IMAGE,
		// MainActivity.TEST_IMAGE_URL});

		// oks.setUrl("http://www.mob.com");
		// oks.setFilePath(CustomShareFieldsPage.getString("filePath",
		// MainActivity.TEST_IMAGE));
		// oks.setComment(CustomShareFieldsPage.getString("comment",
		// context.getString(R.string.share)));
		// oks.setSite(getActivity().getResources().getString(R.string.app_name));
		// oks.setSiteUrl("http://mob.com");
		// oks.setVenueName(CustomShareFieldsPage.getString("venueName",
		// "ShareSDK"));
		// oks.setVenueDescription(CustomShareFieldsPage.getString("venueDescription",
		// "This is a beautiful place!"));
		// oks.setLatitude(23.056081f);
		// oks.setLongitude(113.385708f);
		oks.setSilent(silent);
		// oks.setShareFromQQAuthSupport(shareFromQQLogin);
		oks.setTheme(OnekeyShareTheme.CLASSIC);

		if (platform != null) {
			oks.setPlatform(platform);
		}

		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();

		// 在自动授权时可以禁用SSO方式
		// if(!CustomShareFieldsPage.getBoolean("enableSSO", true))
		oks.disableSSOWhenAuthorize();

		// 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
		oks.setCallback(new OneKeyShareCallback());

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		oks.show(getActivity());
	}

	private void GetandSaveCurrentImage() {
		SHDialog.ShowProgressDiaolg(getActivity(), "正在截图...");
		WindowManager windowManager = getActivity().getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int w = display.getWidth();
		int h = display.getHeight();
		Bitmap Bmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		View decorview = getActivity().getWindow().getDecorView();
		decorview.setDrawingCacheEnabled(true);
		Bmp = decorview.getDrawingCache();
		String SavePath = getSDCardPath() + "/zzh/ScreenImages";
		try {
			File path = new File(SavePath);
			String filepath = SavePath + "/Screen_share.png";
			File file = new File(filepath);
			if (!path.exists()) {
				path.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = null;
			fos = new FileOutputStream(file);
			if (null != fos) {
				Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
				fos.flush();
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		SHDialog.dismissProgressDiaolg();
	}
}
